package com.ruslan.magaz.web.validation;

import java.lang.annotation.Annotation;
import java.util.List;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;

import com.ruslan.magaz.domain.OrderedItem;
import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.ItemService;
import com.ruslan.magaz.service.UserService;

public class GotSomeValidator implements
		ConstraintValidator<GotSome, List<OrderedItem>> {

	@Autowired
	private ItemService itemService;

	@Override
	public void initialize(GotSome constraint) {

	}

	@Override
	public boolean isValid(List<OrderedItem> orderedItems, ConstraintValidatorContext context) {
		for (OrderedItem orderedItem: orderedItems){
			try{
				if (notEnough(orderedItem.getProduct().getProductId(), orderedItem.getProductQuantity())){
					return false;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return true;
	}
	
	
	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}
	
	private boolean notEnough(int productId, int count) throws Exception{
		Integer realCount = itemService.getCountForProductId(productId);
		if (count>realCount) {
			return true;
		}
		return false;
	}

}